package com.example.dubbo.storage.core.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
public class JacksonUtil {

    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static String toJSONString(Object object) {
        if (object == null) {
            return null;
        }
        if (object.getClass() == String.class) {
            return (String) object;
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("JacksonUtil.toJSONString error:{}", object, e);
            return null;
        }
    }

    public static <T> T parseObject(String text, Class<T> tClass) {
        try {
            return OBJECT_MAPPER.readValue(text, tClass);
        } catch (IOException e) {
            log.error("JacksonUtil.parseObject error:{} {}", text, tClass.getName(), e);
            return null;
        }
    }

    public static <E> List<E> parseArray(String text, Class<E> tClass) {
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, tClass));
        } catch (IOException e) {
            log.error("JacksonUtil.parseArray error:{} {}", text, tClass.getName(), e);
            return null;
        }
    }

    public static <K, V> Map<K, V> parseMap(String text, Class<K> kClass, Class<V> vClass) {
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructMapType(Map.class, kClass, vClass));
        } catch (IOException e) {
            log.error("JacksonUtil.parseMap error:{} kClass:{} vClass:{}", text, kClass.getName(), vClass.getName(), e);
            return null;
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> type) {
        try {
            return OBJECT_MAPPER.readValue(text, type);
        } catch (IOException e) {
            log.error("JacksonUtil.parseObject error:{} {}", text, type.getType().getTypeName(), e);
            return null;
        }
    }
}
